<template>
  <div class="talkned">
    <div class="xingming">
      <div class="duixiangname">{{ selectedUserName }}</div>
      <div class="fanhui">
        <el-button size="mini" type="prymary" @click="toPath('./')"
          >首页</el-button
        >
      </div>
    </div>
    <div class="talk" ref="chatContainer">
      <div v-for="(msg, index) in messages" :key="index">
        <!-- 对方消息 -->
        <div v-if="msg.sender !== 'me'" class="duifang">
          <div class="duitou">
            <img src="../../../assets/wechatimgs/yonghu.png" alt="" />
          </div>
          <div class="message">{{ msg.content }}</div>
        </div>

        <!-- 自己消息 -->
        <div v-if="msg.sender === 'me'" class="jiemian">
          <div class="message">{{ msg.content }}</div>
          <div class="tou">
            <img src="../../../assets/wechatimgs/tx.png" alt="" />
          </div>
        </div>
      </div>
    </div>
    <div class="dazi">
      <div class="wenben">
        <el-input
          type="textarea"
          autosize
          style="font-size: 20px; border: none"
          placeholder="请输入内容"
          v-model="textarea"
          @keyup.enter.native="sendMessage"
        >
        </el-input>
      </div>
      <button class="send" @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "TalkNed",
  data() {
    return {
      textarea: "",
      messages: [], // 存储聊天消息
      ws: null, // WebSocket实例
    };
  },
  computed: {
    selectedUserName() {
      return this.$store.state.selectedUser?.name || "请选择联系人";
    },
    selectedUserId() {
      return this.$store.state.selectedUser?.id;
    },
  },
  watch: {
    // 当选择不同联系人时重新连接WebSocket
    selectedUserId(newVal) {
      if (newVal) {
        this.connectWebSocket();
      }
    },
  },
  mounted() {
    if (this.selectedUserId) {
      this.connectWebSocket();
    }
  },
  methods: {
    toPath(path) {
      this.$router.push(path);
    },
    connectWebSocket() {
      if (this.ws) this.ws.close();

      const wsUrl = `ws://websocket.1uu.pw/chat/${this.selectedUserId}`;
      this.ws = new WebSocket(wsUrl);
      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.messages.push({
          content: message.content,
          sender: "other",
          timestamp: new Date().getTime(),
        });
        this.scrollToBottom();
      };

      this.ws.onerror = (error) => {
        console.error("WebSocket error:", error);
      };

      this.ws.onclose = (event) => {
        console.log(
          `WebSocket 连接关闭，代码: ${event.code}, 原因: ${event.reason}`
        );
      };
    },

    // 发送消息
    sendMessage() {
      if (!this.textarea.trim()) return;

      const message = {
        receiverId: this.selectedUserId,
        content: this.textarea.trim(),
        sender: "me",
        timestamp: new Date().getTime(),
      };

      this.ws.send(JSON.stringify(message));
      this.messages.push(message);
      this.textarea = "";
      this.scrollToBottom();
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer;
        container.scrollTop = container.scrollHeight;
      });
    },
    beforeDestroy() {
      if (this.ws) {
        this.ws.close();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.talkned {
  width: 100%;
  height: 100%;

  .xingming {
    width: 100%;
    height: 5%;
    background-color: #fff;
    border-left: 1px solid #000;
    border-bottom: none;
    border-right: 1px solid #000;
    border-top: none;
    display: flex;
    justify-content: space-between;

    .duixiangname {
      width: 40%;
      height: 100%;
      border: 1px solid #000;
      left: 0;
      display: flex;
      align-items: center;
      padding: 0 15px;
      font-size: 16px;
      color: #333;
    }
    .fanhui {
      width: 100px;
      height: 100%;
      right: 0;
    }
  }

  .talk {
    width: 100%;
    height: 75%;
    background-color: #fff;
    border-right: 1px solid #000;
    border-top: 1px solid #000;
    overflow-y: auto;

    .jiemian {
      width: 50%;
      display: flex;
      justify-content: right;
      position: absolute;
      right: 30px;
      margin: 10px 0;
      flex: 1;
      padding: 10px;
      .tou {
        width: 50px;
        height: 50px;
        img {
          width: 50px;
          height: 50px;
          object-fit: cover;
        }
      }
      .message {
        max-width: 40%;
        background: #98fb98;
        margin: 10px 0;
        padding: 10px;
        border-radius: 5px;
      }
    }

    .duifang {
      width: 50%;
      display: flex;
      justify-content: left;
      position: absolute;
      margin: 10px 0;
      flex: 1;
      padding: 10px;
      margin-top: 100px;
      .duitou {
        width: 50px;
        height: 50px;
        img {
          width: 50px;
          height: 50px;
          object-fit: cover;
        }
      }
      .message {
        max-width: 40%;
        background: #98fb98;
        margin: 10px 0;
        padding: 10px;
        border-radius: 5px;
      }
    }
  }

  .dazi {
    width: 100%;
    height: 20%;
    background-color: #fff;
    border-left: none;
    border-bottom: 1px solid #000;
    border-right: 1px solid #000;
    border-top: none;
    position: relative;

    .wenben {
      width: 100%;
      height: 20px;
    }

    .send {
      width: 70px;
      height: 30px;
      background: #98fb98;
      color: #000;
      font-size: 15px;
      position: absolute;
      right: 30px;
      bottom: 20px;
      border: none;
    }
  }
}
</style>
